package cn.cque.controller;

import cn.cque.common.BaseController;
import cn.cque.entity.*;
import cn.cque.service.CartService;
import cn.cque.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: XWC
 * @ClassName: CartController
 * @Date: 2020/10/5
 * @Time: 14:07
 * @Description:
 */
@Controller
@RequestMapping("/cart")
public class CartController extends BaseController {
    @Autowired
    CartService cartService;

    @Autowired
    ProductService productService;

    @RequestMapping("/addItem")
    @ResponseBody
    public InfoResult addItem(String pid,String num) {
        Integer iNum=Integer.parseInt(num);
        Product product = productService.findById(pid);
        double sumPrice=product.getShopPrice()*iNum;
        CartItem cartItem=new CartItem();
        cartItem.setProduct(product);
        cartItem.setNum(iNum);
        cartItem.setSumPrice(sumPrice);
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        if (cart==null){
            cart=new Cart();
            cart= cartService.addItem(cart,cartItem);
        }else {
            cart= cartService.addItem(cart,cartItem);
        }
        request.getSession().setAttribute("cart",cart);
        return InfoResult.SUCCESS();
    }

    @RequestMapping("/list")
    public String cartList(){
        return "/WEB-INF/page/cart";
    }

    @RequestMapping("/deleteItem")
    @ResponseBody
    public InfoResult deleteItem(String pid){
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        cart.delCartItem(pid);
        if (cart.getList().size()==0){
            request.getSession().removeAttribute("cart");
        }else {
            request.getSession().setAttribute("cart",cart);
        }
        return InfoResult.SUCCESS();
    }
}